"""
文件工具函数模块
"""

import os
import shutil
from pathlib import Path
from typing import List, Optional
from datetime import datetime, timedelta


def ensure_directory(directory: Path) -> bool:
    """
    确保目录存在
    
    Args:
        directory: 目录路径
        
    Returns:
        bool: 操作是否成功
    """
    try:
        directory.mkdir(parents=True, exist_ok=True)
        return True
    except Exception as e:
        print(f"创建目录失败: {e}")
        return False


def get_file_size(file_path: Path) -> int:
    """
    获取文件大小
    
    Args:
        file_path: 文件路径
        
    Returns:
        int: 文件大小（字节）
    """
    try:
        return file_path.stat().st_size
    except Exception:
        return 0


def delete_file(file_path: Path) -> bool:
    """
    删除文件
    
    Args:
        file_path: 文件路径
        
    Returns:
        bool: 删除是否成功
    """
    try:
        if file_path.exists():
            file_path.unlink()
        return True
    except Exception as e:
        print(f"删除文件失败: {e}")
        return False


def cleanup_directory(directory: Path, max_age_hours: int = 24) -> int:
    """
    清理目录中的过期文件
    
    Args:
        directory: 目录路径
        max_age_hours: 最大保留时间（小时）
        
    Returns:
        int: 清理的文件数量
    """
    if not directory.exists():
        return 0
    
    cutoff_time = datetime.now() - timedelta(hours=max_age_hours)
    deleted_count = 0
    
    try:
        for file_path in directory.iterdir():
            if file_path.is_file():
                # 获取文件修改时间
                file_mtime = datetime.fromtimestamp(file_path.stat().st_mtime)
                
                if file_mtime < cutoff_time:
                    if delete_file(file_path):
                        deleted_count += 1
    except Exception as e:
        print(f"清理目录失败: {e}")
    
    return deleted_count


def get_safe_filename(filename: str) -> str:
    """
    获取安全的文件名
    
    Args:
        filename: 原始文件名
        
    Returns:
        str: 安全的文件名
    """
    # 移除或替换危险字符
    unsafe_chars = '<>:"/\\|?*'
    safe_filename = filename
    
    for char in unsafe_chars:
        safe_filename = safe_filename.replace(char, '_')
    
    # 限制文件名长度
    if len(safe_filename) > 255:
        name, ext = os.path.splitext(safe_filename)
        safe_filename = name[:255-len(ext)] + ext
    
    return safe_filename


def calculate_directory_size(directory: Path) -> int:
    """
    计算目录总大小
    
    Args:
        directory: 目录路径
        
    Returns:
        int: 目录大小（字节）
    """
    total_size = 0
    
    try:
        for file_path in directory.rglob('*'):
            if file_path.is_file():
                total_size += get_file_size(file_path)
    except Exception as e:
        print(f"计算目录大小失败: {e}")
    
    return total_size


def copy_file(source: Path, destination: Path) -> bool:
    """
    复制文件
    
    Args:
        source: 源文件路径
        destination: 目标文件路径
        
    Returns:
        bool: 复制是否成功
    """
    try:
        # 确保目标目录存在
        ensure_directory(destination.parent)
        
        shutil.copy2(source, destination)
        return True
    except Exception as e:
        print(f"复制文件失败: {e}")
        return False


def move_file(source: Path, destination: Path) -> bool:
    """
    移动文件
    
    Args:
        source: 源文件路径
        destination: 目标文件路径
        
    Returns:
        bool: 移动是否成功
    """
    try:
        # 确保目标目录存在
        ensure_directory(destination.parent)
        
        shutil.move(str(source), str(destination))
        return True
    except Exception as e:
        print(f"移动文件失败: {e}")
        return False